package com.jxy.bean.attribute;

import com.jxy.bean.ClassFile;
import com.jxy.bean.constant.ConstantPoolTag;
import com.jxy.bean.constant.MethodHandleInfo;
import com.jxy.tool.Tool;

import java.io.DataInputStream;
import java.util.Arrays;

/**
 * Attribute属性的BootstrapMethod类型
 */
public class AttributeBootstrapMethod {
    private int bootstrap_method_ref;
    private int num_bootstrap_arguments;
    private int[] bootstrap_arguments;
    private ClassFile cf;

    public AttributeBootstrapMethod(DataInputStream dis, ClassFile cf) {
        this.cf = cf;
        bootstrap_method_ref = Tool.readU2(dis);
        num_bootstrap_arguments = Tool.readU2(dis);
        bootstrap_arguments = getArguments(dis);
    }

    private int[] getArguments(DataInputStream dis) {
        int[] arguments = new int[num_bootstrap_arguments];
        for (int i = 0; i < num_bootstrap_arguments; i++) {
            arguments[i] = Tool.readU2(dis);
        }
        return arguments;
    }

    public boolean valid() {
        //只判断bootstrap_method_ref的指向，参数范围太广，暂不校验
        if (cf.getPools()[bootstrap_method_ref].getTag() != ConstantPoolTag.CONSTANT_MethodHandle.getTag()) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "AttributeBootstrapMethod{" +
                "bootstrap_method_ref=" + cf.getPools()[bootstrap_method_ref] +
                ", num_bootstrap_arguments=" + num_bootstrap_arguments +
                ", bootstrap_arguments=" + Arrays.toString(bootstrap_arguments) +
                '}';
    }
}
